const wordexport = function (wrap) {
    const static_word = {
        mhtml: {
            top:
                'Mime-Version: 1.0\nContent-Base: ' +
                location.href +
                '\nContent-Type: Multipart/related; boundary="NEXT.ITEM-BOUNDARY";type="text/html"\n\n--NEXT.ITEM-BOUNDARY\nContent-Type: text/html; charset="utf-8"\nContent-Location: ' +
                location.href +
                `\n\n
                <!DOCTYPE html>
                <html
                    xmlns:v="urn:schemas-microsoft-com:vml"
                    xmlns:o="urn:schemas-microsoft-com:office:office"
                    xmlns:w="urn:schemas-microsoft-com:office:word"
                    xmlns:m="http://schemas.microsoft.com/office/2004/12/omml"
                    xmlns="http://www.w3.org/TR/REC-html40">\n_html_
                </html>`,
            head:
                `<head>\n
                <meta http-equiv="Content-Type" content="text/html; charset=utf-8">\n
                    <style>\n_styles_\n</style>\n
                    <!--[if gte mso 9]>
                    <xml>
                        <w:WordDocument>
                            <w:View>Print</w:View>
                            <w:TrackMoves>false</w:TrackMoves>
                            <w:TrackFormatting/>
                            <w:ValidateAgainstSchemas/>
                            <w:SaveIfXMLInvalid>false</w:SaveIfXMLInvalid>
                            <w:IgnoreMixedContent>false</w:IgnoreMixedContent>
                            <w:AlwaysShowPlaceholderText>false</w:AlwaysShowPlaceholderText>
                            <w:DoNotPromoteQF/>
                            <w:LidThemeOther>EN-US</w:LidThemeOther>
                            <w:LidThemeAsian>ZH-CN</w:LidThemeAsian>
                            <w:LidThemeComplexScript>X-NONE</w:LidThemeComplexScript>
                            <w:Compatibility>
                                <w:BreakWrappedTables/>
                                <w:SnapToGridInCell/>
                                <w:WrapTextWithPunct/>
                                <w:UseAsianBreakRules/>
                                <w:DontGrowAutofit/>
                                <w:SplitPgBreakAndParaMark/>
                                <w:DontVertAlignCellWithSp/>
                                <w:DontBreakConstrainedForcedTables/>
                                <w:DontVertAlignInTxbx/>
                                <w:Word11KerningPairs/>
                                <w:CachedColBalance/>
                                <w:UseFELayout/>
                            </w:Compatibility>
                            <w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel>
                            <m:mathPr>
                                <m:mathFont m:val="Cambria Math"/>
                                <m:brkBin m:val="before"/>
                                <m:brkBinSub m:val="--"/>
                                <m:smallFrac m:val="off"/>
                                <m:dispDef/>
                                <m:lMargin m:val="0"/>
                                <m:rMargin m:val="0"/>
                                <m:defJc m:val="centerGroup"/>
                                <m:wrapIndent m:val="1440"/>
                                <m:intLim m:val="subSup"/>
                                <m:naryLim m:val="undOvr"/>
                            </m:mathPr>
                        </w:WordDocument>
                    </xml>
                    <![endif]-->
                </head>\n`,
            body: `<body>
            _body_
        </body>`
        }
    }
    const images = []

    const img = wrap.querySelectorAll('img')

    for (let i = 0; i < img.length; i++) {
        const uri = img[i].src

        // Save encoded image to array
        images[i] = {
            type: uri.substring(uri.indexOf(':') + 1, uri.indexOf(';')),
            encoding: uri.substring(uri.indexOf(';') + 1, uri.indexOf(',')),
            location: img[i].src,
            data: uri.substring(uri.indexOf(',') + 1)
        }
    }
    let mhtmlBottom = '\n'
    for (let i = 0; i < images.length; i++) {
        mhtmlBottom += '--NEXT.ITEM-BOUNDARY\n'
        mhtmlBottom += 'Content-Location: ' + images[i].location + '\n'
        mhtmlBottom += 'Content-Type: ' + images[i].type + '\n'
        mhtmlBottom +=
            'Content-Transfer-Encoding: ' + images[i].encoding + '\n\n'
        mhtmlBottom += images[i].data + '\n\n'
    }
    mhtmlBottom += '--NEXT.ITEM-BOUNDARY--'

    // 格式化内容html
    const formattedXml = formateXml(wrap.innerHTML);
    console.log(formattedXml)

    const styles = '';
    const fileContent =
        static_word.mhtml.top.replace(
            '_html_',
            static_word.mhtml.head.replace('_styles_', styles) +
            static_word.mhtml.body.replace('_body_', formattedXml)
            // static_word.mhtml.body.replace('_body_', formattedXml)
        ) + mhtmlBottom
    // Create a Blob with the file contents
    const blob = new Blob([fileContent], {
        type: 'application/msword;charset=utf-8'
    })
    return blob
}

//格式化xml代码
function formateXml (xmlStr) {
    let text = xmlStr;
    //使用replace去空格
    text = '\n' + text.replace(/(<\w+)(\s.*?>)/g, function ($0, name, props) {
        return name + ' ' + props.replace(/\s+(\w+=)/g, " $1");
    }).replace(/>\s*?</g, ">\n<");
    //处理注释
    text = text.replace(/\n/g, '\r').replace(/<!--(.+?)-->/g, function ($0, text) {
        var ret = '<!--' + escape(text) + '-->';
        return ret;
    }).replace(/\r/g, '\n');
    //调整格式  以压栈方式递归调整缩进
    var rgx = /\n(<(([^\\?]).+?)(?:\s|\s*?>|\s*?(\/)>)(?:.*?(?:(?:(\/)>)|(?:<(\/)\2>)))?)/mg;
    var nodeStack = [];
    var output = text.replace(rgx, function ($0, all, name, isBegin, isCloseFull1, isCloseFull2, isFull1, isFull2) {
        var isClosed = (isCloseFull1 == '/') || (isCloseFull2 == '/') || (isFull1 == '/') || (isFull2 == '/');
        var prefix = '';
        if (isBegin == '!') {//!开头
            prefix = setPrefix(nodeStack.length);
        } else {
            if (isBegin != '/') {///开头
                prefix = setPrefix(nodeStack.length);
                if (!isClosed) {//非关闭标签
                    nodeStack.push(name);
                }
            } else {
                nodeStack.pop();//弹栈
                prefix = setPrefix(nodeStack.length);
            }
        }
        var ret = '\n' + prefix + all;
        return ret;
    });
    var prefixSpace = -1;
    var outputText = output.substring(1);
    //还原注释内容
    outputText = outputText.replace(/\n/g, '\r').replace(/(\s*)<!--(.+?)-->/g, function ($0, prefix, text) {
        if (prefix.charAt(0) == '\r')
            prefix = prefix.substring(1);
        text = unescape(text).replace(/\r/g, '\n');
        var ret = '\n' + prefix + '<!--' + text.replace(/^\s*/mg, prefix) + '-->';
        return ret;
    });
    outputText = outputText.replace(/\s+$/g, '').replace(/\r/g, '\r\n');
    return outputText;
}

//计算头函数 用来缩进
function setPrefix (prefixIndex) {
    var result = '';
    var span = '    ';//缩进长度
    var output = [];
    for (var i = 0; i < prefixIndex; ++i) {
        output.push(span);
    }
    result = output.join('');
    return result;
}

export default wordexport
